package main;  

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;

import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Status;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;

public class ProjectListResource extends ServerResource {  

	final String templateHeader = "<br/><h1><span style=\"color: rgb(0, 0, 205);\">Welcome to our real estate platform!!</span></h1><div><span style=\"color: rgb(0, 0, 205); \">Following real estates are available at the moment:</span></div><div><span style=\"color: rgb(0, 0, 205); \"><br /></span></div>" +
			"<div><span style=\"color: rgb(0, 0, 205); \"><table style=\"border-collapse:collapse;width:50%;margin-left:50px;\"><tbody><tr><td style=\"border:#000000 1px solid\"><span style=\"font-weight: bold; \">ID</span></td><td style=\"border:#000000 1px solid\"><span style=\"font-weight: bold; \">Address</span></td>" + 
			"<td style=\"border:#000000 1px solid\"><span style=\"font-weight: bold; \">Description</span></td><td style=\"border:#000000 1px solid\"><span style=\"font-weight: bold; \">Price</span></td></tr><tr><td style=\"border:#000000 1px solid\"></td><td style=\"border:#000000 1px solid\"></td><td style=\"border:#000000 1px solid\"></td>" + 
			"<td style=\"border:#000000 1px solid\"></td></tr>";
	String templateFooter = "</tbody></table><br /></span></div>";

	@Post
	public void acceptJsonRepresentation(JsonRepresentation entity) {

		JSONObject json = null;

		try {
			String address = null;
			String description =null;
			String price= null;
			System.out.println(entity.toString());
			json = entity.getJsonObject();

			address = (String) json.getString("address");
			description = (String) json.getString("description");
			price = (String) json.getString("price");
			//	        System.out.println("Address: " + json.get("address"));
			//	        System.out.println("description: " + json.get("description"));
			System.out.println(json.toString());
			// business logic and persistence
			writeFile(address, description, price);


		} catch (JSONException e) {
			setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
			return;
		} 

	}

	private void writeFile(String address, String description, String price){
		try{	
			FileWriter fstream = new FileWriter("project_db.txt", true);
			BufferedWriter out = new BufferedWriter(fstream);

			int id = 0;
			FileReader freader = new FileReader("project_db.txt");
			BufferedReader in = new BufferedReader(freader);
			while (in.readLine()!=null){
				id++;
			}
			in.close();

			out.write(id +";"+ address +";"+ description+ ";"+ price);
			out.newLine();
			out.flush();	
			//Close the output stream
			out.close();
		}catch (Exception e){//Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
	}


	//	@Post("json")
	//	public Representation post() throws ResourceException {
	//	    try {
	//	        Representation entity = getRequestEntity();
	//	        JsonRepresentation represent = new JsonRepresentation(entity);
	//	        JSONObject jsonobject = represent.toJsonObject();
	//	        JSONObject json  = jsonobject.getJSONObject("request");
	//
	//	        Representation response = new StringRepresentation("Well done");
	//	        getResponse().setStatus(Status.SUCCESS_ACCEPTED);
	////	        //ScanRequestAck ack = new ScanRequestAck();
	////	        //ack.statusURL = "http://localhost:8080/status/2713";
	////	        JsonRepresentation rep = new JsonRepresentation(jsonobject);
	////	        rep.setMediaType(MediaType.APPLICATION_JSON);
	////	        
	//	        getResponse().setEntity(response);
	//	        
	//	        return response;
	//
	//	    } catch (Exception e) {
	//	        getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
	//	        return null;
	//	    }
	//	}

	@Get("html")  
	public String represent() { 
		String respond;
		try{
			String address = null;
			String description =null;
			String price = null;
			int id = 0;
			FileReader freader = new FileReader("project_db.txt");
			BufferedReader in = new BufferedReader(freader);
			String line = null;
			respond = templateHeader; 
			while ((line = in.readLine()) !=null){
				String delims = ";";
				String[] tokens = line.split(delims);
				id= Integer.valueOf(tokens[0]);
				address = tokens[1];
				description = tokens[2];
				 price = tokens[3];
				String dataRow = "<tr><td style=\"border:#000000 1px solid\"><span style=\"font-weight: bold; \">"+ id + "</span></td><td style=\"border:#000000 1px solid\"><span style=\"font-weight: bold; \">"+address+"</span></td>" + 
						"<td style=\"border:#000000 1px solid\"><span style=\"font-weight: bold; \">"+description+"</span></td><td style=\"border:#000000 1px solid\"><span style=\"font-weight: bold; \">"+price+" &#x80;</span></td></tr><tr><td style=\"border:#000000 1px solid\"></td><td style=\"border:#000000 1px solid\"></td><td style=\"border:#000000 1px solid\"></td>" + 
						"<td style=\"border:#000000 1px solid\"></td></tr>";
				respond += dataRow;
			}
			in.close();
			respond += templateFooter;

		}
		catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

		return respond;

	}

	public static String stringToHTMLString(String string) {
		StringBuffer sb = new StringBuffer(string.length());
		// true if last char was blank
		boolean lastWasBlankChar = false;
		int len = string.length();
		char c;

		for (int i = 0; i < len; i++)
		{
			c = string.charAt(i);
			if (c == ' ') {
				// blank gets extra work,
				// this solves the problem you get if you replace all
				// blanks with &nbsp;, if you do that you loss 
				// word breaking
				if (lastWasBlankChar) {
					lastWasBlankChar = false;
					sb.append("&nbsp;");
				}
				else {
					lastWasBlankChar = true;
					sb.append(' ');
				}
			}
			else {
				lastWasBlankChar = false;
				//
				// HTML Special Chars
				if (c == '"')
					sb.append("&quot;");
				else if (c == '&')
					sb.append("&amp;");
				else if (c == '<')
					sb.append("&lt;");
				else if (c == '>')
					sb.append("&gt;");
				else if (c == '\n')
					// Handle Newline
					sb.append("&lt;br/&gt;");
				else {
					int ci = 0xffff & c;
					if (ci < 160 )
						// nothing special only 7 Bit
						sb.append(c);
					else {
						// Not 7 Bit use the unicode system
						sb.append("&#");
						sb.append(new Integer(ci).toString());
						sb.append(';');
					}
				}
			}
		}
		return sb.toString();
	}
}